package tt.dz.tcp.socket.timeoff;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import tt.dz.service.imp.middleware.instruction.Ev3c2Instructions;
import tt.dz.service.imp.middleware.instruction.Ev3cInstructions;
import tt.dz.service.imp.middleware.instruction.Instruction;
import tt.dz.service.imp.middleware.instruction.InstructionType;
import tt.dz.service.imp.middleware.vo.ProtocolVersion;
import tt.dz.service.imp.middleware.vo.UnSendingMessage;

/**
 * Created by luoyp on 2016/6/13.
 */
@Component
public class MsgTimeOffHandlerFactory implements ApplicationContextAware
{
	private static Log log = LogFactory.getLog(MsgTimeOffHandlerFactory.class);

	private static ApplicationContext applicationContext;

	public static MsgTimeOffHandler getTimeOffHandler(UnSendingMessage message)
	{
		String command = message.getCommand();
		AbstractMsgTimeOffHandler handler = new EmptyMsgTimeOffHandler();
		if (message.getProtocolVersion() == ProtocolVersion.Version_2)
		{
			Ev3c2Instructions instruction = Ev3c2Instructions.parse(command);

			if (instruction == Ev3c2Instructions.Reserve)
				handler = applicationContext.getBean(Ev3c2ReservationMsgTimeOffHandler.class);
			else if (instruction == Ev3c2Instructions.Charge)
				handler = applicationContext.getBean(Ev3c2ChargeMsgTimeOffHandler.class);

		}
		else if (message.getProtocolVersion() == ProtocolVersion.Version_1)
		{
			Ev3cInstructions instruction = Ev3cInstructions.parse(command);

			if (instruction == Ev3cInstructions.Reserve)
				handler = applicationContext.getBean(Ev3cReservationMsgTimeOffHandler.class);
			else if (instruction == Ev3cInstructions.Charge)
				handler = applicationContext.getBean(Ev3cChargeMsgTimeOffHandler.class);
		}
		else
			return null;

		handler.setChargerId(message.getChargerId());
		handler.setMessage(message.getMessage());
		log.info(handler);
		log.info(handler.getChargerId());
		log.info(handler.getMessage());

		return handler;
	}

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException
	{
		log.debug("Init application context");
		applicationContext = context;
	}
}
